﻿using System;
using System.Security.Cryptography;
using System.Web;

namespace M.SSO
{
	/// <summary>
	/// 提供单点登陆支持
	/// </summary>
	public static class AuthProvider
	{
		#region SSO验证
		/// <summary>
		/// 根据字符串验证
		/// </summary>
		/// <param name="encyptUserJsonString">加密后的用户实例的Json字符串，BASE64编码</param>
		/// <param name="signedUserJsonString">签名的用户实例Json字符串，BASE64编码</param>
		/// <param name="svrPublicKey">服务端密钥，此处使用服务端公钥</param>
		/// <param name="clientPrivateKey">客户端密钥，此处使用客户端私钥</param>
		/// <returns></returns>
		public static AuthVerifyResult GetAuthVerifyResult(string encyptUserJsonString, string signedUserJsonString, string svrPublicKey, string clientPrivateKey)
		{
			AuthVerifyResult result = new AuthVerifyResult();
			// 使用客户端私钥解密
			byte[] userBytes = null;
			using (var rsa = new RSACryptoServiceProvider())
			{
				rsa.FromXmlString(clientPrivateKey);
				userBytes = rsa.Decrypt(Convert.FromBase64String(encyptUserJsonString), false);
			}
			// 使用服务端公钥验证签名
			using (var rsa = new RSACryptoServiceProvider())
			{
				rsa.FromXmlString(svrPublicKey);
				result.VerifyResult = rsa.VerifyData(userBytes, "SHA1", Convert.FromBase64String(signedUserJsonString));
			}
			if (result.VerifyResult)
			{
				string[] userStringArr = System.Text.Encoding.UTF8.GetString(userBytes).Split('|');
				result.User.ID = userStringArr[0];
				result.User.Code = userStringArr[1];
				result.User.Name = userStringArr[2];
				result.User.Station = userStringArr[3];
			}
			return result;
		}
		/// <summary>
		/// 从验证服务器回传验证
		/// </summary>
		/// <returns></returns>
		public static AuthVerifyResult GetAuthVerifyResultFromRedirect()
		{
			//string redirectUrl = AuthProvider.GetRedirectUrl();
			string encrypted = AuthProvider.GetEncryptedString();
			string signed = AuthProvider.GetSignedString();

			// 解密及验证
			return AuthProvider.GetAuthVerifyResult(
				encrypted,
				signed,
				"<RSAKeyValue><Modulus>ogDE8D/pVsV35+SFC+D2G7/nr3XcrESIdQlrGZzrEuwduyIGYvqnHMyJgRqrlDStYvYmboytDg1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iVAmna1rVhdp0Wq5HG3cujNnM3LcSaCZWXrhYIW7txyso44/GOdHCtRvUZnHKIUKxz4fmsWcuhHik1jptATTO43WmUsb0COuHozMXdhxHqkeSkxfTx/jPdv4AsvM8bdeShYdqE=</DP><DQ>PutItmZyDLjAoN0Ypbr47o7F2GWjLRGeSLUvMLnWlBaGAmMRZwz0qw9/Qokiyl1da9Lg2AARLz+N+6+yTsR1l+kc98fAaVmZpE5NZFflMBzwUXCSPWXJfJjGuhSJg8oa3rtQ8eSUbRLt6Br1Vq3nLXgKauuaBCEZ9mo04qnPvAk=</DQ><InverseQ>Uxfghrccva+OFZtLYYwvNYY0cOCRpirqTZWvvKsJxxzFfLSNXQmf2lO9RlnCHpYULJ8DwGWsE4WOTkh/QaRRKCCfRU1imArqmd/ysG5sZuGN5CnVj1LILyP0PabS1exdoOMwB7xAG77hXRMmTZ1olRZRSBUh2Wo7zvmRKorotOA=</InverseQ><D>HXdEOA9AXHdD997BaLsPlrf8VMw70+8Cj99sBS7UpIr46Ie9q9uJ6O9AT+GZnw5mCjus1BtxYrg0EXijfcf6N4TZuPW3xv4x3iceUMgPqta1c2b6cXTGNB9PO8dicy8f35UPqiOKazy1iw7HeFTWFzjPyATH1LNgu5c883Pwi69imPRR7xloVGVEbgMXMFHXwbNpM55yRyCpqbjCwmLokrSxo6wxWyC1eivxURZqVjcvYlLpeorlwA/kFPkRwneODQcGkaCq/kcFxDFAJ65lU54ZdywxdC5jOm1Qx+rerkBeSuHkh2S3Z8DWEuT1I55Roog7CNL1lc4xs0wr1V9cqQ==</D></RSAKeyValue>");
		}
		/// <summary>
		/// 获取跳转页面地址
		/// </summary>
		/// <returns></returns>
		public static string GetRedirectUrl()
		{
			return Web.Util.GetFormString("redirecturl");
		}
		/// <summary>
		/// 获取加密字符串
		/// </summary>
		/// <returns></returns>
		public static string GetEncryptedString()
		{
			return Web.Util.GetFormString("encrypt");
		}
		/// <summary>
		/// 获取签名字符串
		/// </summary>
		/// <returns></returns>
		public static string GetSignedString()
		{
			return Web.Util.GetFormString("sign");
		}
		#endregion

		#region SSO Cookie Helper

		/// <summary>
		/// 设置 SSO Cookie 
		/// </summary>
		/// <param name="values">Cookie集合</param>
		/// <param name="cookieName">Cookie名字</param>
		public static void SetSSOCookie(System.Collections.Specialized.NameValueCollection values, string cookieName)
		{
			SetSSOCookie(values, cookieName);
		}
		/// <summary>
		/// 设置 SSO Cookie
		/// </summary>
		/// <param name="values">Cookie集合</param>
		/// <param name="cookieName">Cookie名字</param>
		/// <param name="domain">域名</param>
		public static void SetSSOCookie(System.Collections.Specialized.NameValueCollection values, string cookieName, string domain)
		{
			HttpCookie cookie = new HttpCookie(cookieName);
			foreach (string key in values.Keys)
				cookie.Values.Add(key, values[key]);
			if (!string.IsNullOrEmpty(domain))
				cookie.Domain = domain;
			HttpContext.Current.Response.Cookies.Add(cookie);
		}
		/// <summary>
		/// 获取 SSO Cookie
		/// </summary>
		/// <param name="cookieName"></param>
		/// <returns></returns>
		public static System.Collections.Specialized.NameValueCollection GetSSOCookie(string cookieName)
		{
			if (HttpContext.Current.Request.Cookies[cookieName] != null)
				return HttpContext.Current.Request.Cookies[cookieName].Values;
			return null;
		}

		#endregion

	}
}
